package com.example.highclasscomponent;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class SpinnerActivity extends AppCompatActivity implements  AdapterView.OnItemSelectedListener {

    //定义下拉列表需要显示的文本数组
    public static final String[] starArray={"水星","金星","地球","火星","木星","土星"};
    private Spinner spn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner);
        spn = findViewById(R.id.spn);
        //创建数组适配器
        ArrayAdapter<String> startAdapter=new ArrayAdapter<>(this,R.layout.item_select,starArray);
        //设置适配器给下拉框
        spn.setAdapter(startAdapter);
        //设置初始选项为第一项
        spn.setSelection(0);
        //设置选择事件
        spn.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(this, "您选择的是："+starArray[position], Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}